public class HashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;
        public Node(int key,int val){
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array  =new Node[10];
    public int usedSise;
    public static final double loadFactor = 0.75;

    //插入
    public void push(int key,int val){
        Node node = new Node(key,val);
        //1.找位置
        int index = key%array.length;
        //2.遍历数组
        Node cur = array[index];
       /* if(cur==null){
            //采用头插法
            array[index] = node;
            usedSise++;
            return;
        }*/
        while (cur!=null){
            if(cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //找不到的情况下,这里使用的是头插法
        node.next = array[index];
        array[index] = node;
        usedSise++;

        if(doLoadFactor()>=0.75){
            //计算负载因子,并且处理
            reSize();
        }
    }

    private void reSize(){
        Node[] newArray = new Node[array.length*2];
        //重新进行哈希

        for (int i = 0; i < array.length; i++) {
            Node cur= array[i];
            while (cur!=null){
                 int index = cur.key%newArray.length;
                 //进行头插法
                cur.next = newArray[index];
                newArray[index] =cur;
                cur=cur.next;
            }
        }
        array = newArray;
    }

    private double doLoadFactor(){
        return  usedSise*1.0/array.length;
    }

    public int get(int key){
        int index = key%array.length;
        Node cur = array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
